package com.app.view_controller;

import java.util.ArrayList;
import java.util.Calendar;
import com.app.alarm.R;
import com.app.model.AlarmDataManager;
import com.app.model.AlarmDataManager.AlarmLoader;
import com.app.service.AlarmService;
import com.app.service.HandleAlarmNotificationService;
import com.app.util.ApplicationMediator;
import com.app.util.MessageListenerAdapter;
import com.app.util.VolumeManager;
import com.app.view_controller.custom_view.DayChooserWithFont;
import com.app.view_controller.custom_view.DayChooserWithFont.OnDayCheckedListener;
import com.app.view_controller.custom_view.TextViewWithFont;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.format.Time;
import android.transition.Transition;
import android.transition.Transition.TransitionListener;
import android.transition.Scene;
import android.transition.TransitionInflater;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.CheckBox;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Switch;

import android.widget.Toast;
import android.widget.ToggleButton;

@SuppressLint("ValidFragment")
public class AlarmSetterDialog extends Fragment implements OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener, OnDayCheckedListener,
		OnGlobalLayoutListener {

	private static final String TAG = "ALARMSETTERDIALOG";
	private static final boolean DEBUG = true;
	private static final String TIME_TEXT_VIEW_TAG = "time textview tag";
	private static final String ALARM_ENABLE_SWITCH = "alarm enable switch";
	private static final String ALARM_VOLUME = "alarm volume";
	private static final String INCREMENTAL_VOLUME = "incremental volume";
	private static final String ALARM_SEEK_BAR = "alarm seekbar";
	private static final String POSTPONE_INTERVAL = "postpone interval";
	private static final String PICK_UP_POSTPONE = "pick up postpone";
	private static final String AUTOMATIC_ROTATION = "automatic rotation";
	private static final String CONTROL_RINGTONE = "control ringtone";
	private static final String RINGTONE_SEEKBAR = "ringtone seekbar";
	private static final String CONTROL_NOTIFICATION = "control notification";
	private static final String NOTIFICATION_SEEKBAR = "notification seekbar";
	protected static final String URI_FROM_TONE_DIALOG = "uri from tone dialog";
	private static final Object CONTROL_ALARM_VOLUME = "control alarm volume";
	private static final String CONTROL_RINGTONE_VIBRATION = "control ringtone vibration";
	private static final String CONTROL_NOTIFICATION_VIBRATION = "control notification vibration";












	private int mpadding;
	private LinearLayout mFragmentLLayout;
	private android.widget.RelativeLayout.LayoutParams mLLayoutLParams;
	private Button mExitButton;
	private Bundle mDataFromList;
	private ApplicationMediator mMediator;
	private TextViewWithFont mTimeTextView;
	private Switch mAlarmEneableSwitch;
	private Button mAlarmRingtoneButton;
	private CheckBox mIncrementalVolumeBox;
	private SeekBar mAlarmVolumeSeekBar;
	private Button mPostPoneIntervalButton;
	private CheckBox mPickUpToPostponeBox;
	private CheckBox mAutomaticRotationBox;
	private ToggleButton mControlRingtoneButton;
	private ToggleButton mControlNotificationButton;
	private SeekBar mRingtoneSeekBar;
	private SeekBar mNotificationSeekBar;
	private Button mAdvancedButton;
	private AlarmDataManager mAlarmData;
	private View dialogView;
	private boolean onProgressChangedCanBeCalled;
	private Button mAutomaticRotationInfoButton;
	private DayChooserWithFont mDayChooser;
	private ToggleButton mAlarmControlVolumeButton;
	private boolean fragmentIsClosing;
	private ToggleButton mRingtoneVibrationButton;
	private ToggleButton mNotificationVibrationButton;
	private LinearLayout mRingtoneControlLayout;
	private LinearLayout mNotificaiotnControlLayout;
	private VolumeManager mVolume;
	private LinearLayout mDialogActionBar;
	private boolean onCreateViewCalled = false;
	private RelativeLayout mconttt;
	private LinearLayout mLayout;
	private ScrollView mRootLayout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMediator = ApplicationMediator.getInstance();
		mVolume = VolumeManager.getVolumeManagerInstance(getActivity());
		setHasOptionsMenu(true);
		mDataFromList = getArguments();

		String AlarmString = mDataFromList.getString(ContentActivity.TO_DIALOG_ALARM_DATA);
		mAlarmData = AlarmLoader.convertFromJSON(AlarmString, getActivity());
		// mMediator.setMessagesListener(this,
		// ContentActivity.TO_DIALOG_ANIMATION_DATA, new
		// MessageListenerAdapter() {
		// @Override
		// public void onMessageReceivedWithData(Bundle data) {
		// mDataFromList = data;
		// super.onMessageReceivedWithData(data);
		// mDataFromList = data;
		// }
		// });
		mMediator.setMessagesListener(this, ContentActivity.RECEIVE_TIME_FROM_TIME_PICKER, new MessageListenerAdapter() {
			@Override
			public void onMessageReceivedWithData(int hours, int minutes) {
				String h, m;
				h = m = "";
				if (minutes < 10)
					m = "0";
				if (hours < 10)
					h = "0";
				mTimeTextView.setText(h + hours + ":" + m + minutes);
				mAlarmData.setCalendarAlarm(hours, minutes);
				if (mAlarmData.isAlarmEneable()) {
					mAlarmData.setAlarm();
					mAlarmEneableSwitch.setChecked(true);
					Calendar c = Calendar.getInstance();
					long difference = mAlarmData.getCalendarAlarm().getTimeInMillis() - c.getTimeInMillis();
					Time t = new Time();
					t.set(difference);
					// if (DEBUG)
					// Log.d(TAG, "CALENDARIO ATTUALE" + c + " " + difference);
					// if (DEBUG)
					// Log.d(TAG, "CALENDARIO ALLARME " +
					// mAlarmData.getCalendarAlarm());
					int sDiff = (int) difference / 1000;
					int hDiff = (int) sDiff / 3600;
					int mDiff = (int) ((sDiff - hDiff * 3600) / 60);
					Toast.makeText(getActivity(), "Allarme attivato fra " + hDiff + " ore e " + mDiff + " minuti.", Toast.LENGTH_SHORT).show();
					// if (DEBUG)
					// Log.d(TAG, "hdiff e mindiff " + hDiff + " " + mDiff);
				}
				super.onMessageReceivedWithData(hours, minutes);
			}
		});
		mMediator.setMessagesListener(this, URI_FROM_TONE_DIALOG, new MessageListenerAdapter() {
			@Override
			public void onMessageReceivedWithData(String uriString) {
				mAlarmData.setAlarmtoneUri(Uri.parse(uriString));
				mAlarmData.savetoStorage();
			}
		});
		final AlarmSetterDialog mFragment = this;
		mMediator.setMessagesListener(this, ContentActivity.UPDATE_ALARMLIST_AND_DIALOG, new MessageListenerAdapter() {
			@Override
			public void onMessageReceived() {
				if (DEBUG)
					Log.d(TAG, "Update alarm list and dialog called");
				// TODO Must create the remove listeners in ApplicationMediator
				if (getActivity() != null) {
					ArrayList<AlarmDataManager> list = AlarmLoader.getStoredAlarmList(getActivity());
					for (int i = 0; i < list.size(); i++) {
						if (mAlarmData.getAlarmId().equals(list.get(i).getAlarmId())) {
							mAlarmData = list.get(i);
							mControlRingtoneButton.setOnCheckedChangeListener(null);
							mControlNotificationButton.setOnCheckedChangeListener(null);
							mControlNotificationButton.setChecked(mAlarmData.isControlNotificationEneable());
							mControlRingtoneButton.setChecked(mAlarmData.isControlRingtoneEneable());
							Scene s = new Scene((ViewGroup) dialogView.findViewById(R.id.alarm_l_layout));
							TransitionManager.go(s);
							if (!mControlRingtoneButton.isChecked())
								mRingtoneControlLayout.setVisibility(View.GONE);
							if (!mControlNotificationButton.isChecked())
								mNotificaiotnControlLayout.setVisibility(View.GONE);
							mControlRingtoneButton.setOnCheckedChangeListener(mFragment);
							mControlNotificationButton.setOnCheckedChangeListener(mFragment);
							break;
						}
					}
				}

				super.onMessageReceived();
			}
		});

		fragmentIsClosing = false;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		dialogView = inflater.inflate(R.layout.alarm_dialog, container, false);
		mFragmentLLayout = (LinearLayout) dialogView.findViewById(R.id.alarm_l_layout);
		mLLayoutLParams = (RelativeLayout.LayoutParams) mFragmentLLayout.getLayoutParams();
		mDialogActionBar = (LinearLayout) dialogView.findViewById(R.id.action_bar_l_dialog);
		mExitButton = (Button) dialogView.findViewById(R.id.actionbar_exit_button);
		mRootLayout = (ScrollView) dialogView.findViewById(R.id.dialog_root);

		mTimeTextView = (TextViewWithFont) dialogView.findViewById(R.id.dialog_time_text_view);
		mAlarmEneableSwitch = (Switch) dialogView.findViewById(R.id.dialog_alarm_eneable_switch);
		mDayChooser = (DayChooserWithFont) dialogView.findViewById(R.id.dialog_alarm_day_chooser);
		mAlarmRingtoneButton = (Button) dialogView.findViewById(R.id.alarm_ringtone);
		mIncrementalVolumeBox = (CheckBox) dialogView.findViewById(R.id.is_incremental_volume);
		mAlarmControlVolumeButton = (ToggleButton) dialogView.findViewById(R.id.alarm_control_volume_level);
		mAlarmVolumeSeekBar = (SeekBar) dialogView.findViewById(R.id.alarm_seekbar);
		mPostPoneIntervalButton = (Button) dialogView.findViewById(R.id.ripetition_interval);
		mPickUpToPostponeBox = (CheckBox) dialogView.findViewById(R.id.shake_to_postpone);
		mAutomaticRotationBox = (CheckBox) dialogView.findViewById(R.id.automatic_rotation);
		mAutomaticRotationInfoButton = (Button) dialogView.findViewById(R.id.automatic_orientation_info);
		mControlRingtoneButton = (ToggleButton) dialogView.findViewById(R.id.ringtone_volume);
		mControlNotificationButton = (ToggleButton) dialogView.findViewById(R.id.notification_volume);
		mRingtoneVibrationButton = (ToggleButton) dialogView.findViewById(R.id.ringtone_vibration_button);
		mRingtoneSeekBar = (SeekBar) dialogView.findViewById(R.id.ringtone_seekbar);
		mNotificationVibrationButton = (ToggleButton) dialogView.findViewById(R.id.notification_vibration_button);
		mNotificationSeekBar = (SeekBar) dialogView.findViewById(R.id.notification_seekbar);

		mRingtoneControlLayout = (LinearLayout) dialogView.findViewById(R.id.ringtone_vibration_linear_layout);
		mNotificaiotnControlLayout = (LinearLayout) dialogView.findViewById(R.id.notification_vibration_linear_layout);

		mTimeTextView.setTag(TIME_TEXT_VIEW_TAG);
		mAlarmEneableSwitch.setTag(ALARM_ENABLE_SWITCH);
		mAlarmRingtoneButton.setTag(ALARM_VOLUME);
		mIncrementalVolumeBox.setTag(INCREMENTAL_VOLUME);
		mAlarmControlVolumeButton.setTag(CONTROL_ALARM_VOLUME);
		mAlarmVolumeSeekBar.setTag(ALARM_SEEK_BAR);
		mPostPoneIntervalButton.setTag(POSTPONE_INTERVAL);
		mPickUpToPostponeBox.setTag(PICK_UP_POSTPONE);
		mAutomaticRotationBox.setTag(AUTOMATIC_ROTATION);
		mControlRingtoneButton.setTag(CONTROL_RINGTONE);
		mRingtoneVibrationButton.setTag(CONTROL_RINGTONE_VIBRATION);
		mRingtoneSeekBar.setTag(RINGTONE_SEEKBAR);
		mControlNotificationButton.setTag(CONTROL_NOTIFICATION);
		mNotificationVibrationButton.setTag(CONTROL_NOTIFICATION_VIBRATION);
		mNotificationSeekBar.setTag(NOTIFICATION_SEEKBAR);

		mMediator.setMessagesListener(this, ContentActivity.BACK_BUTTON_PRESSED, new MessageListenerAdapter() {
			@Override
			public void onMessageReceived() {
				mExitButton.performClick();
				super.onMessageReceived();
			}
		});
		mExitButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (DEBUG)
					Log.d(TAG, "Exit from dialog called");
				mAlarmData.savetoStorage();
				fragmentIsClosing = true;
				onProgressChangedCanBeCalled = false;
				ObjectAnimator anim = ObjectAnimator.ofInt(mRootLayout, "ScrollY", -500);

				anim.start();
				Rect cellBounds = mDataFromList.getParcelable(ContentActivity.CELL_BOUNDS);
				Rect listBounds = mDataFromList.getParcelable(ContentActivity.LIST_BOUNDS);
				// Create a layoutParams with the clicked cell width, height and
				// position on the screen
				final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(cellBounds.right - cellBounds.left, cellBounds.bottom
						- cellBounds.top);
				lp.setMargins(cellBounds.left, cellBounds.top, listBounds.right - cellBounds.right, listBounds.bottom - cellBounds.bottom);
				final Transition t = TransitionInflater.from(getActivity()).inflateTransition(R.transition.floating_transition);
				t.addListener(new TransitionListenerAdapter() {

					@Override
					public void onTransitionStart(Transition arg0) {
						mMediator.sendMessage(ContentActivity.START_DIALOG_CLOSURE);
						mDialogActionBar.animate().translationYBy(-mDialogActionBar.getHeight())
								.setDuration(ContentActivity.ANIMATION_DURATION_MEDIUM);
						mIncrementalVolumeBox.animate().alpha(0f).setDuration(ContentActivity.ANIMATION_DURATION_SHORT);
						final ObjectAnimator anim2 = ObjectAnimator.ofFloat(mAlarmRingtoneButton, "alpha", 1f, 0f);
						anim2.setDuration(ContentActivity.ANIMATION_DURATION_SHORT);
						anim2.start();
						anim2.addListener(new AnimatorListenerAdapter() {

							@Override
							public void onAnimationEnd(Animator animation) {
								if (DEBUG)
									Log.d(TAG, "onanimationEnd called");

								mAlarmRingtoneButton.setText("    Advanced");
								mAlarmRingtoneButton.animate().alpha(1f).setDuration(ContentActivity.ANIMATION_DURATION_SHORT);
								mIncrementalVolumeBox.setVisibility(View.VISIBLE);
							}

						});
					}

					@Override
					public void onTransitionEnd(Transition arg0) {
						// Message to the ActivityContent that hides this
						// fragment
						mMediator.sendMessage(ContentActivity.EXIT_CALL);
						// Message to ListAdapter to update the list view
						if (DEBUG)
							Log.d(TAG, "dialog alarm id " + mAlarmData.getAlarmId());
						mMediator.sendMessageWithAttachedData(ContentActivity.UPDATE_LIST, mAlarmData.convertTOJSON());
					}

				});

				anim.addListener(new AnimatorListenerAdapter() {
					@Override
					public void onAnimationEnd(Animator animation) {
						// Set the original LayoutPArams to the floating view(This will be animated)
						Scene s = new Scene(mFragmentLLayout);
						TransitionManager.go(s, t);
						mFragmentLLayout.setLayoutParams(lp);
						super.onAnimationEnd(animation);
					}
				});
			}
		});

		dialogView.getViewTreeObserver().addOnGlobalLayoutListener(this);
		onCreateViewCalled = true;

		return dialogView;
	}

	private void configureViewsStatus() {
		if (DEBUG)
			Log.d(TAG, "ConfigureViewStatus called");
		Calendar c = mAlarmData.getCalendarAlarm();
		String h, m;
		h = m = "";
		if (c.get(Calendar.MINUTE) < 10)
			m = "0";
		if (c.get(Calendar.HOUR_OF_DAY) < 10)
			h = "0";
		mTimeTextView.setText(h + c.get(Calendar.HOUR_OF_DAY) + ":" + m + c.get(Calendar.MINUTE));
		mAlarmEneableSwitch.setChecked(mAlarmData.isAlarmEneable());
		for (int i = 1; i < 7; i++)
			mDayChooser.setDayChecked(i, mAlarmData.isRepeatedDay(i));
		mIncrementalVolumeBox.setChecked(mAlarmData.isIncrementalVolume());
		mAlarmControlVolumeButton.setChecked(mAlarmData.isControlledAlarmVolume());
		mAlarmVolumeSeekBar.setProgress(mAlarmData.getAlarmVolumeLevel());
		mPostPoneIntervalButton.setOnClickListener(this);
		mPickUpToPostponeBox.setChecked(mAlarmData.isPickUpToPostpone());
		mAutomaticRotationBox.setChecked(mAlarmData.isRotationDisabled());
		mControlRingtoneButton.setChecked(mAlarmData.isControlRingtoneEneable());
		mRingtoneVibrationButton.setChecked(mAlarmData.isRingtoneVibrationActive());
		mRingtoneSeekBar.setProgress(mAlarmData.getRingtoneVolumeLevel());
		mControlNotificationButton.setChecked(mAlarmData.isControlNotificationEneable());
		mNotificationVibrationButton.setChecked(mAlarmData.isNotificationVibrationActive());
		mNotificationSeekBar.setProgress(mAlarmData.getNotificationVolumeLevel());
		if (!mAlarmControlVolumeButton.isChecked())
			mAlarmVolumeSeekBar.setVisibility(View.GONE);
		if (!mControlRingtoneButton.isChecked())
			mRingtoneControlLayout.setVisibility(View.GONE);
		if (!mControlNotificationButton.isChecked())
			mNotificaiotnControlLayout.setVisibility(View.GONE);

		onProgressChangedCanBeCalled = true;

		// Set the max value for the seekbars.
		AudioManager audio = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
		mAlarmVolumeSeekBar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_ALARM));
		mNotificationSeekBar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION));
		mRingtoneSeekBar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_RING));

	}

	@Override
	public void onResume() {
		mTimeTextView.setOnClickListener(this);
		mAlarmEneableSwitch.setOnCheckedChangeListener(this);
		mDayChooser.setOnDayCheckedListener(this);
		mAlarmRingtoneButton.setOnClickListener(this);
		mIncrementalVolumeBox.setOnCheckedChangeListener(this);
		mAlarmControlVolumeButton.setOnCheckedChangeListener(this);
		mAlarmVolumeSeekBar.setOnSeekBarChangeListener(this);
		mPickUpToPostponeBox.setOnCheckedChangeListener(this);
		mAutomaticRotationBox.setOnCheckedChangeListener(this);
		mControlRingtoneButton.setOnCheckedChangeListener(this);
		mRingtoneVibrationButton.setOnCheckedChangeListener(this);
		mRingtoneSeekBar.setOnSeekBarChangeListener(this);
		mControlNotificationButton.setOnCheckedChangeListener(this);
		mNotificationVibrationButton.setOnCheckedChangeListener(this);
		mNotificationSeekBar.setOnSeekBarChangeListener(this);
		super.onResume();

	}

	@Override
	public void onClick(View v) {
		String tag = (String) v.getTag();
		if (DEBUG)
			Log.d(TAG, "onCLickCalled with the tag " + tag);
		if (tag.equals(TIME_TEXT_VIEW_TAG)) {
			TimeDialog mDialog = new TimeDialog();
			Bundle b = new Bundle();
			b.putLong("ciao", mAlarmData.getCalendarAlarm().getTimeInMillis());
			mDialog.setArguments(b);
			mDialog.show(getFragmentManager(), "TimeDialog");
		}
		if (tag.equals(ALARM_VOLUME)) {
			AlarmtoneDialogFragment tone = new AlarmtoneDialogFragment();
			tone.show(getFragmentManager(), mAlarmData.convertTOJSON());
		}
		if (POSTPONE_INTERVAL.equals(tag)) {
			final Dialog numberPickerDialog = new Dialog(getActivity());
			numberPickerDialog.setTitle(R.string.Postpone_interval);
			numberPickerDialog.setContentView(R.layout.number_picker_dialog);
			Button setButton = (Button) numberPickerDialog.findViewById(R.id.set_postpone_interval_button);
			Button cancelButton = (Button) numberPickerDialog.findViewById(R.id.cancel_postpone_interval_button);
			final NumberPicker picker = (NumberPicker) numberPickerDialog.findViewById(R.id.postpone_picker);
			picker.setMaxValue(60);
			picker.setMinValue(0);
			picker.setValue(mAlarmData.getPostponeTimeInMinutes());
			setButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mAlarmData.setPostponeTime(picker.getValue());
					numberPickerDialog.dismiss();
				}
			});
			cancelButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					numberPickerDialog.dismiss();
				}
			});
			numberPickerDialog.show();
		}
		mAlarmData.savetoStorage();
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		mAlarmData.savetoStorage();
		String tag = (String) seekBar.getTag();
		if (DEBUG)
			Log.d(TAG, "onStopTrackingTouch called with tag " + tag);
		if (RINGTONE_SEEKBAR.equals(tag))
			if (mAlarmData.isAlarmEneable() && mAlarmData.isControlRingtoneEneable())
				mVolume.setStreamVolume(VolumeManager.STREAM_RING, mAlarmData.getRingtoneVolumeLevel(), 0);
		if (NOTIFICATION_SEEKBAR.equals(tag))
			if (mAlarmData.isAlarmEneable() && mAlarmData.isControlNotificationEneable())
				mVolume.setStreamVolume(VolumeManager.STREAM_NOTIFICATION, mAlarmData.getNotificationVolumeLevel(), 0);

	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		//DO NOTHING
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		String tag = (String) seekBar.getTag();
		if (DEBUG)
			Log.d(TAG, "progress vale " + progress + "tag vale " + tag);
		if (fromUser && onProgressChangedCanBeCalled) {
			if (ALARM_SEEK_BAR.equals(tag))
				mAlarmData.setAlarmVolumeLevel(progress);
			if (RINGTONE_SEEKBAR.equals(tag))
				mAlarmData.setRingtoneVolumeLevel(progress);
			if (NOTIFICATION_SEEKBAR.equals(tag))
				mAlarmData.setNotificationVolumeLevel(progress);
		}
		mAlarmData.savetoStorage();

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		String tag = (String) buttonView.getTag();
		if (DEBUG)
			Log.d(TAG, "onCheckedChanged called with tag " + tag + " and value " + isChecked);
		if (ALARM_ENABLE_SWITCH.equals(tag)) {

			if (isChecked) {
				mAlarmData.setAlarm();
				if (mAlarmData.isControlRingtoneEneable())
					mVolume.setStreamVolume(VolumeManager.STREAM_RING, mAlarmData.getRingtoneVolumeLevel(), 0);
				if (mAlarmData.isControlNotificationEneable())
					mVolume.setStreamVolume(VolumeManager.STREAM_NOTIFICATION, mAlarmData.getNotificationVolumeLevel(), 0);

				Calendar c = Calendar.getInstance();
				long difference = mAlarmData.getCalendarAlarm().getTimeInMillis() - c.getTimeInMillis();
				Time t = new Time();
				t.set(difference);
				int sDiff = (int) difference / 1000;
				int hDiff = (int) sDiff / 3600;
				int mDiff = (int) ((sDiff - hDiff * 3600) / 60);
				Toast.makeText(getActivity(), "Allarme attivato fra " + hDiff + " ore e " + mDiff + " minuti.", Toast.LENGTH_SHORT).show();

				Intent startNotification = new Intent(getActivity(), HandleAlarmNotificationService.class);
				startNotification.setAction(HandleAlarmNotificationService.START_NOTIFICATION);
				startNotification.putExtra(HandleAlarmNotificationService.ALARM_DATA, mAlarmData.getAlarmId());
				getActivity().startService(startNotification);
			} else {
				mAlarmData.removeAlarm();
				if (mAlarmData.isControlRingtoneEneable())
					mVolume.restoreDefaultVolumeLevel(VolumeManager.STREAM_RING);
				if (mAlarmData.isControlNotificationEneable())
					mVolume.restoreDefaultVolumeLevel(VolumeManager.STREAM_NOTIFICATION);
				NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
				mNotificationManager.cancel(HandleAlarmNotificationService.ALARM_SET_NOTIFICATION_ID);
			}
		}
		if (INCREMENTAL_VOLUME.equals(tag)) {

			if (isChecked)
				mAlarmData.setIncrementalVolume(true);
			else
				mAlarmData.setIncrementalVolume(false);
		}
		if (CONTROL_ALARM_VOLUME.equals(tag)) {
			if (isChecked) {
				mAlarmData.setControlAlarmVolume(true);
				mAlarmVolumeSeekBar.setVisibility(View.VISIBLE);
			} else {
				mAlarmData.setControlAlarmVolume(false);
				mAlarmVolumeSeekBar.setVisibility(View.GONE);
			}
		}
		if (PICK_UP_POSTPONE.equals(tag)) {
			if (isChecked)
				mAlarmData.setPickUpToPostpone(true);
			else
				mAlarmData.setPickUpToPostpone(false);
		}
		if (AUTOMATIC_ROTATION.equals(tag)) {
			if (isChecked)
				mAlarmData.setBlockRotationEneable(true);
			else
				mAlarmData.setBlockRotationEneable(false);
		}
		if (CONTROL_RINGTONE.equals(tag)) {
			if (isChecked) {
				mAlarmData.setControlRingtoneEneable(true);
				mRingtoneControlLayout.setVisibility(View.VISIBLE);
				if (mAlarmData.isAlarmEneable())
					mVolume.setStreamVolume(VolumeManager.STREAM_RING, mAlarmData.getRingtoneVolumeLevel(), 0);

			} else {
				mAlarmData.setControlRingtoneEneable(false);
				mRingtoneControlLayout.setVisibility(View.GONE);
				if (mAlarmData.isAlarmEneable())
					mVolume.restoreDefaultVolumeLevel(VolumeManager.STREAM_RING);
			}
		}
		if (CONTROL_RINGTONE_VIBRATION.equals(tag)) {
			mAlarmData.setRingtoneVibration(isChecked);
		}
		if (CONTROL_NOTIFICATION.equals(tag)) {
			if (isChecked) {
				mAlarmData.setControlNotificationEneable(true);
				mNotificaiotnControlLayout.setVisibility(View.VISIBLE);
				if (mAlarmData.isAlarmEneable())
					mVolume.setStreamVolume(VolumeManager.STREAM_NOTIFICATION, mAlarmData.getNotificationVolumeLevel(), 0);
			} else {
				mAlarmData.setControlNotificationEneable(false);
				mNotificaiotnControlLayout.setVisibility(View.GONE);
				if (mAlarmData.isAlarmEneable())
					mVolume.restoreDefaultVolumeLevel(VolumeManager.STREAM_NOTIFICATION);
			}
		}
		if (CONTROL_NOTIFICATION_VIBRATION.equals(tag)) {
			mAlarmData.setNotificationVibration(isChecked);
		}
		mAlarmData.savetoStorage();
	}

	@Override
	public void onDayCheckedChanged(View v, int day, boolean isChecked) {

		if (isChecked) {
			mAlarmData.setRepeatDay(day);
			if (mAlarmData.isAlarmEneable())
				mAlarmData.setAlarm();
		} else {
			mAlarmData.removeRepeatDay(day);
			mAlarmData.removeAlarm();
		}
		AlarmLoader.saveAlarmToStorage(mAlarmData);
	}

	@Override
	public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
		if (nextAnim != R.animator.request_fragment_transition_animation)
			return null;

		// Get the informations for the animation
		Rect cellBounds = mDataFromList.getParcelable(ContentActivity.CELL_BOUNDS);
		Rect listBounds = mDataFromList.getParcelable(ContentActivity.LIST_BOUNDS);
		// Create a layoutParams with the clicked cell width, height and
		// position on the screen
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(cellBounds.right - cellBounds.left, cellBounds.bottom - cellBounds.top);
		lp.setMargins(cellBounds.left, cellBounds.top, listBounds.right - cellBounds.right, listBounds.bottom - cellBounds.bottom);
		Animator anim = ObjectAnimator.ofFloat(mFragmentLLayout, View.TRANSLATION_X, 0f);
		anim.setDuration(10);
		// Set lp to the fragment dialog in order to have it exactly above the
		// clicked cell.
		if (enter) {
			if (DEBUG)
				Log.d(TAG, "Entrato nell'Enter");
			configureViewsStatus();
			mFragmentLLayout.setLayoutParams(lp);
			// It is impossible to use a Transition here, because the system will try to animate the <code>mFloatingView.setLayoutParams(lp);</code>
			// We don't want this to happen, so a solution is to put the Transition code inside an animator listener.
			anim.addListener(new AnimatorListenerAdapter() {

				@Override
				public void onAnimationStart(Animator animation) {
					super.onAnimationStart(animation);
					mDialogActionBar.setVisibility(View.VISIBLE);
					mDialogActionBar.setY(-mDialogActionBar.getHeight());
					mDialogActionBar.animate().translationYBy(mDialogActionBar.getHeight()).setDuration(1000);

				}

				@Override
				public void onAnimationEnd(Animator animation) {
					if (DEBUG)
						Log.d(TAG, "Transition begins");

					mIncrementalVolumeBox.setAlpha(0.1f);
					final ObjectAnimator anim = ObjectAnimator.ofFloat(mAlarmRingtoneButton, "alpha", 1f, 0f);
					anim.setDuration(ContentActivity.ANIMATION_DURATION_MEDIUM);
					anim.start();
					anim.addListener(new AnimatorListenerAdapter() {

						@Override
						public void onAnimationEnd(Animator animation) {
							if (DEBUG)
								Log.d(TAG, "onanimationEnd called");

							mAlarmRingtoneButton.setText(getResources().getString(R.string.Select_ringtone));
							mAlarmRingtoneButton.animate().alpha(1f).setDuration(ContentActivity.ANIMATION_DURATION_SHORT);
							mIncrementalVolumeBox.setVisibility(View.VISIBLE);
							mIncrementalVolumeBox.animate().alpha(1f).setDuration(ContentActivity.ANIMATION_DURATION_SHORT);
						}

					});
					Transition t = TransitionInflater.from(getActivity()).inflateTransition(R.transition.floating_transition);
					TransitionManager.beginDelayedTransition(mFragmentLLayout, t);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							mMediator.sendMessage(ContentActivity.HIDE_CLICKED_CELL);
						}
					}, 0);
					// Set the original LayoutParams to the floating view(This will be animated)

					mFragmentLLayout.setLayoutParams(mLLayoutLParams);

				}
			});
		} else {
			// DO NOTHING because the exit animation is created in the onClick()
			// method of the exit button
		}
		return anim;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.clear();

	}

	@Override
	public void onGlobalLayout() {
		if (onCreateViewCalled) {
			mDialogActionBar.setY(-mDialogActionBar.getHeight());
			mDialogActionBar.animate().translationYBy(mDialogActionBar.getHeight()).setDuration(ContentActivity.ANIMATION_DURATION_MEDIUM);
		}
		onCreateViewCalled = false;

	}

}